<template>
  <div class="user-management">
    <!-- 搜索栏 -->
    <el-card shadow="never" class="search-card">
      <el-form :model="searchForm" inline label-width="95px">
        <el-form-item label="用户名" class="pb-3.5 w-1/3 flex-shrink-0 2xl:w-1/4">
          <el-input v-model="searchForm.username" placeholder="请输入用户名" clearable />
        </el-form-item>
        <el-form-item label="状态" class="pb-2 w-1/3 flex-shrink-0 2xl:w-1/4">
          <el-select v-model="searchForm.status" placeholder="请选择状态" clearable>
            <el-option label="启用" value="1" />
            <el-option label="禁用" value="0" />
          </el-select>
        </el-form-item>
        <el-form-item
          label="创建时间"
          class="pb-3.5 w-1/3 flex-shrink-0 trzansition-all duration-300 2xl:w-1/4"
          v-show="!hidden"
        >
          <el-date-picker
            v-model="searchForm.createTime"
            type="daterange"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="yyyy-MM-dd"
            value-format="yyyy-MM-dd"
            clearable
          />
        </el-form-item>
        <el-form-item
          label=""
          class="pb-3.5 w-1/3 flex-shrink-0 trzansition-all duration-300 2xl:w-1/4"
          v-show="!hidden"
        ></el-form-item>
        <el-form-item
          label=""
          class="pb-3.5 w-1/3 flex-shrink-0 trzansition-all duration-300 2xl:w-1/4"
          v-show="!hidden"
        ></el-form-item>
        <el-form-item
          label=""
          class="pb-3.5 w-1/3 flex-shrink-0 trzansition-all duration-300 2xl:w-1/4"
          v-show="!hidden"
        >
        </el-form-item>
        <el-form-item class="pb-3.5 w-1/3 flex-shrink-0 2xl:w-1/4">
          <div class="flex justify-end w-full">
            <el-button @click="resetSearch">重置</el-button>
            <el-button type="primary" @click="handleSearch">搜索</el-button>
            <div
              class="inline-flex items-center ml-2 text-blue cursor-pointer"
              @click="hidden = !hidden"
            >
              <span>{{ !hidden ? "收起" : "展开" }}</span>
              <div
                class="transition-transform duration-300"
                :class="{ 'rotate-180': !hidden }"
              >
                <svg
                  xmlns="http://www.w3.org/2000/svg"
                  width="24"
                  height="24"
                  viewBox="0 0 24 24"
                  fill="none"
                  stroke="currentColor"
                  stroke-width="2"
                  stroke-linecap="round"
                  stroke-linejoin="round"
                  class="lucide lucide-chevron-down-icon lucide-chevron-down size-4"
                >
                  <path d="m6 9 6 6 6-6"></path>
                </svg>
              </div>
            </div>
          </div>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 数据表格 -->
    <el-card shadow="never">
      <div class="flex justify-between mb-4">
        <div><h5>用户列表</h5></div>
        <!-- 操作栏 -->
        <div>
          <el-button type="primary" @click="handleCreate">
            <el-icon><Plus /></el-icon>新增用户
          </el-button>
          <el-button :disabled="!selectedIds.length" @click="handleBatchDelete">
            <el-icon><Delete /></el-icon>批量删除
          </el-button>
          <el-button @click="searchTable" type="primary" circle title="搜索">
            <el-icon><Search /></el-icon>
          </el-button>
          <el-button @click="refreshTable" circle title="刷新">
            <el-icon><Refresh /></el-icon>
          </el-button>
        </div>
      </div>

      <el-table
        v-loading="loading"
        :data="UsersList"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="50" />
        <el-table-column prop="username" label="用户名" min-width="120" />
        <el-table-column prop="nickname" label="昵称" min-width="120" />
        <el-table-column prop="email" label="邮箱" min-width="180" />
        <el-table-column prop="phone" label="手机号" min-width="120" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-switch
              v-model="row.isActive"
              style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949"
              inline-prompt
              size="default"
              active-text="已启用"
              inactive-text="已禁用"
            />
          </template>
        </el-table-column>
        <el-table-column prop="createdAt" label="创建时间" width="180" />
        <el-table-column label="操作" width="180" fixed="right" align="center">
          <template #default="{ row }">
            <el-button size="small" @click="handleEdit(row)">编辑</el-button>
            <el-button size="small" type="danger" @click="handleDelete(row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination
        v-model:current-page="pagination.current"
        v-model:page-size="pagination.size"
        :total="pagination.total"
        :page-sizes="[10, 20, 50, 100]"
        class="mt-3.5"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </el-card>
    <el-drawer
      v-model="dialog.visible"
      :title="dialog.mode === 'create' ? '新增用户' : '编辑用户'"
      :direction="dialog.direction"
      :before-close="() => (dialog.visible = false)"
    >
      <div>
        <!-- 用户表单对话框 -->
        <RoleFormDialog
          ref="formDialogRef"
          :form-data="dialog.formData"
          :mode="dialog.mode"
          @success="refreshTable"
        />
      </div>
      <template #footer>
        <div style="flex: auto" class="flex items-center justify-end space-x-2">
          <el-button @click="dialog.visible = false">取消</el-button>
          <el-button type="primary" @click="handleConfirm">确定</el-button>
        </div>
      </template>
    </el-drawer>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted } from "vue";
import { ElMessage, ElMessageBox, ElNotification } from "element-plus";
import { Plus, Delete, Refresh } from "@element-plus/icons-vue";
import RoleFormDialog from "@/components/ui/role/RoleFormDialog.vue";
import type { RoleItem, CreateRoleParams } from "@/api/types/role";
import * as Api from "@/api/index";

const formDialogRef = ref<InstanceType<typeof RoleFormDialog>>();
// --控制搜索条件，显示、隐藏--
const hidden = ref(false);

// 搜索表单
const searchForm = reactive({
  username: "",
  status: "",
  createTime: "",
});

// 分页数据
const pagination = reactive({
  current: 1,
  size: 10,
  total: 0,
});

// 表格数据
const loading = ref(false);
const UsersList = ref<RoleItem[]>([]);
const selectedIds = ref<string[]>([]);

// 对话框控制
const dialog = reactive({
  visible: true,
  mode: "create" as "create" | "edit",
  direction: "rtl",
  formData: {} as RoleItem,
});
const searchTable = () => {};
// 获取用户列表
const fetchUserList = async () => {
  try {
    loading.value = true;
    const params = {
      ...searchForm,
      page: pagination.current,
      limit: pagination.size,
    };
    const res: any = await Api.getUserList(params);
    console.log("用户列表：", res);
    UsersList.value = res.users.map((item:any) => ({
      ...item,
      isActive: item.status === "active", // 直接展开原属性并添加新字段
    }));
    console.log("用户列表：", UsersList.value);
    pagination.total = res?.pagination?.total || 0;
  } finally {
    loading.value = false;
  }
};

// 搜索相关方法
const handleSearch = () => {
  pagination.current = 1;
  fetchUserList();
};

const resetSearch = () => {
  searchForm.username = "";
  searchForm.status = "";
  handleSearch();
};

// 表格相关方法
const handleSelectionChange = (selection: RoleItem[]) => {
  selectedIds.value = selection.map((item) => item.id);
};

const refreshTable = () => {
  fetchUserList();
};

// 分页方法
const handleSizeChange = (size: number) => {
  pagination.size = size;
  fetchUserList();
};

const handleCurrentChange = (current: number) => {
  pagination.current = current;
  fetchUserList();
};

// 操作相关方法
const handleCreate = () => {
  dialog.mode = "create";
  dialog.formData = {} as RoleItem;
  dialog.visible = true;
};

const handleEdit = (row: RoleItem) => {
  dialog.mode = "edit";
  dialog.formData = { ...row };
  dialog.visible = true;
};

const handleDelete = async (row: RoleItem) => {
  try {
    await ElMessageBox.confirm(`确定删除用户 ${row.username} 吗？`, "提示", {
      type: "warning",
    });
    await Api.deleteUser(row.id);
    ElMessage.success("删除成功");
    refreshTable();
  } catch {
    // 用户取消
  }
};

const handleBatchDelete = async () => {
  try {
    await ElMessageBox.confirm(
      `确定删除选中的 ${selectedIds.value.length} 个用户吗？`,
      "提示",
      {
        type: "warning",
      }
    );
    const res = await Api.batchDeleteUsers(selectedIds.value);
    console.log(res);
    ElMessage.success("删除成功");
    refreshTable();
  } catch {
    // 用户取消
  }
};
const handleConfirm = async () => {
  console.log("确认提交");
  if (formDialogRef.value) {
    const success = await formDialogRef.value.submit();
    console.log("提交结果:", success);
    if (success) {
      ElNotification({
        title: "Success",
        message: "This is a success message",
        type: "success",
      });
      setTimeout(() => {
        dialog.visible = false;
      }, 500);
      refreshTable();
    }
  }
};
// 初始化加载
onMounted(() => {
  fetchUserList();
});
</script>

<style lang="scss" scoped>
.user-management {
  .search-card {
    margin-bottom: 12.5px;

    :deep(.el-form-item) {
      margin-bottom: 0;
      margin-right: 0px;
    }
  }

  .operation-card {
    margin-bottom: 10px;
  }
}

:deep(.el-drawer__footer) {
  border-top: 1px solid var(--el-border-color-light);
}
</style>
